import json
import cv2
import os



def box_overlap(box1, box2, overlap_threshold=0.4):
    # 计算两个矩形框的重叠面积占比
    x1, y1, w1, h1 = box1['x1'], box1['y1'], box1['x2'] - box1['x1'], box1['y2'] - box1['y1']
    x2, y2, w2, h2 = box2['x1'], box2['y1'], box2['x2'] - box2['x1'], box2['y2'] - box2['y1']

    overlap_x = max(0, min(x1 + w1, x2 + w2) - max(x1, x2))
    overlap_y = max(0, min(y1 + h1, y2 + h2) - max(y1, y2))

    overlap_area = overlap_x * overlap_y
    area1 = w1 * h1
    area2 = w2 * h2

    overlap_ratio1 = overlap_area / area1
    overlap_ratio2 = overlap_area / area2
    # print(overlap_ratio1)
    # print(overlap_ratio2)
    # 判断重叠面积占比是否超过阈值
    if overlap_ratio1 > overlap_threshold or overlap_ratio2 > overlap_threshold:
        return True
    else:
        return False

def find_tracked_person(person, track_results):
    for track_result in track_results:
        if track_result['name'] != 'person':
            continue
        current_box = person['box']
        track_box = track_result['box']
        if box_overlap(current_box, track_box):
            return track_result
    return None

def save_pairs(origin_frame, track_results, match_results, matches, output_dir):
    new_matches = []
    for match_result in match_results:
        person = match_result['person']
        person['box']={
            "x1": person['box'][0],
            "y1": person['box'][1],
            "x2": person['box'][2],
            "y2": person['box'][3]
        }
        object = match_result['object']
        tracked_person = find_tracked_person(person, track_results)
        if tracked_person is None:
            person['track_id'] = f'unfound_{person["image_id"]}'
            tracked_person = person

        match = {
            'person': tracked_person,
            'object': object
        }
        matches.append(match)
        new_matches.append(match)

        save_cropped_image(origin_frame, tracked_person, output_dir)
        save_cropped_image(origin_frame, object, output_dir)
    return matches, new_matches

import random
def save_pairs_face(origin_frame, track_results, proj_face, output_dir):
    person = {
        'box': {
            "x1": proj_face[0],
            "y1": proj_face[1],
            "x2": proj_face[2],
            "y2": proj_face[3]
        }
    }
    tracked_person = find_tracked_person(person, track_results)

    if tracked_person is None:
        person['track_id'] = f'unfound_{random.randint(1, 1000)}'
        tracked_person = person
    
    save_cropped_image(origin_frame, tracked_person, output_dir, "_face")
    pass


def save_cropped_image(origin_frame, detection, output_dir, face=""):
    track_id = detection["track_id"]
    # Extract bounding box coordinates
    x1, y1, x2, y2 = map(int, (detection["box"]["x1"], detection["box"]["y1"], detection["box"]["x2"], detection["box"]["y2"]))
    # print(f"{x1} {y1} {x2} {y2}")
    # Crop the object from the frame
    cropped_object = origin_frame[y1:y2, x1:x2]
    
    image_path = f"{output_dir}{track_id}{face}.jpg"

    # Check if the image already exists
    if not os.path.exists(image_path):
        cv2.imwrite(image_path, cropped_object)